package com.ruoyi.network;
import com.ruoyi.common.utils.HexUtil;
import com.ruoyi.network.message.ReceivedMessage;
import com.ruoyi.ufox.domain.BisDevice;
import com.ruoyi.ufox.domain.BisDeviceData;
import com.ruoyi.ufox.service.IBisDeviceDataService;
import com.ruoyi.ufox.service.IBisDeviceService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 消息总线
 * 处理和硬件交互的各种消息
 */
@Component
public class MessageBus {


    @Autowired
    private OnlineDeviceManager onlineDeviceManager;

    @Autowired
    private IBisDeviceDataService deviceDataService;
    @Autowired
    private IBisDeviceService deviceService;


    /**
     * 创建线程池，增强系统处理速度
     */
    private ExecutorService executorService = Executors.newFixedThreadPool(10);

    /**
     * 异步发送消息
     * @param hex
     * @param deviceCode
     */
    public void asyncSendMessage(String hex, String deviceCode){

        executorService.execute(new Runnable() {
            @Override
            public void run() {

                sendMessage(hex, deviceCode);
            }
        });
    }

    /**
     * 同步发送消息
     * @param hex
     * @param deviceCode
     */
    public void sendMessage(String hex, String deviceCode){

        if(onlineDeviceManager.checkDeviceOnline(deviceCode)){

            hex = hex.replaceAll(" ", "");
            byte[] sendData = HexUtil.hexStringToByteArray(hex);

            ByteBuf sendData2 = Unpooled.copiedBuffer(sendData);

            Channel channel = onlineDeviceManager.getChannelByDeviceCode(deviceCode);

            if(channel!=null){

                System.out.println("服务器向客户端发送消息："+hex);

                channel.writeAndFlush(sendData2);
            }
        }else{
            System.out.println("设备不在线，无法发送消息");
        }
    }


    /**
     * 异步处理接收到的消息
     * @param message
     */
    public void asyncHandleReceivedMessage(ReceivedMessage message){

        executorService.execute(new Runnable() {
            @Override
            public void run() {

                handleReceivedMessage(message);
            }
        });
    }

    /**
     * 同步处理接收到的消息
     * @param message
     */
    public void handleReceivedMessage(ReceivedMessage message){


        switch (message.getCmdType()){

            case QUERY_TEMPERATURE:
                System.out.println("发送的是获取温度命令");
                break;
            case BEAT_HEART:
                System.out.println("发送的是心跳命令");
                String content = message.getDataHex();//160716081a221b215e00000000
                int temp = Integer.parseInt(content.substring(12, 14), 16);
                int humidity = Integer.parseInt(content.substring(14, 16), 16);
                int lightIntensity = Integer.parseInt(content.substring(16, 18), 16);

                long fanSwitch = Integer.parseInt(content.substring(18, 20), 16);
                long pumpSwitch = Integer.parseInt(content.substring(20, 22), 16);
                long rollingSwitch = Integer.parseInt(content.substring(22, 24), 16);

                int lightValue = Integer.parseInt(content.substring(24, 26), 16);

                BisDeviceData bisDeviceData = new BisDeviceData();
                bisDeviceData.setDeviceId(onlineDeviceManager.getDeviceByCode(message.getDeviceCode()).getDeviceId());
                bisDeviceData.setCollectTime(new Date());
                bisDeviceData.setHumidity(BigDecimal.valueOf(humidity));
                bisDeviceData.setTemperature(BigDecimal.valueOf(temp));
                bisDeviceData.setLightIntensity(BigDecimal.valueOf(lightIntensity));
                bisDeviceData.setLightValue(lightValue);

                //将心跳写入数据库insertBisDeviceData
                deviceDataService.insertBisDeviceData(bisDeviceData);
                BisDevice device = new BisDevice();
                device.setDeviceId(bisDeviceData.getDeviceId());
                device.setFanStatus(fanSwitch);
                device.setPumpStatus(pumpSwitch);
                device.setRollerShutterStatus(rollingSwitch);
                device.setLighterStatus(lightValue==0?0L:1L);
                deviceService.updateBisDevice(device);

                break;
            //...
            default:
                System.out.println("未知类型的命令");
        }

        System.out.println("消息处理完毕........................");
    }


}
